/**
 * @Author liangzai
 * @Description:
 */
public class HashBuck<K,V> {

    static class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int useSize;

    public static final double DEFAULT_LOAD_FACTOR = 0.75f;

    private double isFull(){
        return useSize*1.0/ array.length;
    }

    public void push(K key,V val){
        int hashcode = key.hashCode();
        int index = hashcode % array.length;
        Node pcur = array[index];
        while (pcur != null) {
            if(pcur.key.equals(key)){
                pcur.val = val;
                return ;
            }
            pcur = pcur.next;
        }
        Node<K,V> newnode = new Node(key,val);
        newnode.next = array[index];
        array[index] = newnode;
        useSize++;
        if(isFull() >= 0.75){
            resize();
        }
    }

    public void resize(){
        Node<K,V>[] newarray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node pcur = array[i];
            while(pcur != null){
                int hashcode = pcur.key.hashCode();
                int index = hashcode % newarray.length;
                Node pcurN = pcur;
                pcur.next = newarray[index];
                newarray[index] = pcur;
                pcur = pcurN.next;
            }
        }
        array = newarray;
    }

    public V getVal(K key){
        int hashcode = key.hashCode();
        int index = hashcode % array.length;
        Node<K,V> pcur = array[index];
        while (pcur != null) {
            if(pcur.key.equals(key)){
                return pcur.val;
            }
        }
        return null;
    }
}
